﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TK.Mqtt.Client
{
    /// <summary>
    /// 支持多个多个MQTT客户端连接
    /// </summary>
    public class MultiMqttClientWrapper : IMultiMqttClientWrapper
    {
        private readonly List<MqttClientWrapper> _clientWrapperList;
        private readonly MqttConfig _mqttConfig;
        private readonly IDataHandler _dataHandler;

        /// <summary>
        /// ctor
        /// </summary>
        public MultiMqttClientWrapper(IOptions<MqttConfig> options, IServiceProvider serviceProvider)
        {
            _clientWrapperList = new List<MqttClientWrapper>();
            _mqttConfig = options.Value;
            _dataHandler = serviceProvider.GetService<IDataHandler>();
            _mqttConfig.ConfigList.ForEach(m =>
            {
                _clientWrapperList.Add(new MqttClientWrapper(m));
            });
        }

        /// <summary>
        /// 启动mqtt客户端
        /// </summary>
        public async Task StartClientAsync()
        {
            foreach (MqttClientWrapper client in _clientWrapperList)
            {
                client.ReceiveData += ClientReceiveData;
                await client.StartAsync();
            }
        }

        /// <summary>
        /// 内部数据接收
        /// </summary>
        private void ClientReceiveData(CallbackData obj)
        {
            if (_dataHandler != null)
            {
                _dataHandler.ReceiveDataAync(obj).ConfigureAwait(false);
            }
        }

        #region IDisposable
        public void Dispose()
        {
            _clientWrapperList.ForEach((client) =>
            {
                client.ReceiveData -= ClientReceiveData;
                client.Dispose();
            });
            _clientWrapperList.Clear();
        }
        #endregion
    }
}
